import { getProtocolWsUrl } from "./ws";

class SpeakSocket {
  speechSocket: WebSocket | null = null;
  constructor() {
    this.speechSocket = null;
  }
  public start(text: string) {
    return new Promise((reslove, reject) => {
      this.speechSocket = new WebSocket(
        getProtocolWsUrl(
          `${window.location.host}/cnpc-web/supgpt-app/chat-tool-voice-speak/`
        )
      );
      this.speechSocket.binaryType = "arraybuffer";
      this.speechSocket.onopen = () => {
        reslove(this.speechSocket);
        const language = "zh-CN";
        const request = {
          text: text,
          language: language,
        };
        if (this.speechSocket) this.speechSocket.send(JSON.stringify(request));
      };
      this.speechSocket.onerror = (err) => {
        reject(err);
      };
    });
  }
  public send(data: any) {
    if (!this.speechSocket) return;
    if (this.speechSocket.readyState === 1) {
      this.speechSocket.send(data);
    }
  }
  public close() {
    if (!this.speechSocket) return;
    this.speechSocket.close();
    this.speechSocket = null;
  }
}

export default SpeakSocket;
